//
//  RdbSettingViewController.swift
//  rdb-led-banner
//
//  Created by GJC on 2025/4/21.
//

import UIKit
import SnapKit

class RdbSettingViewController: BaseViewController,UITableViewDataSource,UITableViewDelegate {

    var modelList: [[RdbSettingModel]] = [[]]
    var isLayoutChanged: Bool = false
    var isArbic: Bool = Locale.isRTL()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.addSubview(tableView)
        self.tableView.snp.makeConstraints{
            $0.edges.equalToSuperview()
        }
        self.reloadData()
        
        NotificationCenter.default.addObserver(self, selector: #selector(themeChange), name: .rdbThemeColorChange, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(languageChange), name: .rdbLanguageChange, object: nil)
    }
    @objc func languageChange(){
        if Locale.isRTL() == self.isArbic {
            self.isLayoutChanged = false
        } else {
            self.isLayoutChanged = true
            self.isArbic = Locale.isRTL()
        }
        self.reloadData()
    }
    @objc func themeChange(){
        self.reloadData()
    }
    
    func reloadData(){
        modelList = getSettingsList()
        self.tableView.reloadData()
    }
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .insetGrouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.rowHeight = 50
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = RdbColor.background.main.color
        tableView.register(RdbSettingTableViewCell.self, forCellReuseIdentifier: RdbSettingTableViewCell.identified)
       return tableView
    }()
 
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return modelList.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let items = modelList[section]
        return items.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let items = modelList[indexPath.section]
        let model = items[indexPath.row]
        guard let cell = tableView.dequeueReusableCell(withIdentifier: RdbSettingTableViewCell.identified,for: indexPath) as? RdbSettingTableViewCell else {
            return UITableViewCell()
        }
        cell.configData(model)
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let items = modelList[indexPath.section]
        let model = items[indexPath.row]
        switch model.identifier {
        case "rateUs":
            self.writeReview()
        case "share":
            self.shareApp()
        case "language":
            let languageSelectController = RdbLanguageSelectController()
            languageSelectController.title = model.title
            languageSelectController.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(languageSelectController, animated: true)
        case "theme":
            let themeSelectController = RdbThemeSelectController()
            themeSelectController.title = model.title
            self.present(themeSelectController,animated: true)
        case "privacyPolicy":
            let webViewController = RdbViewUtils.shared.createPrivacyPolicy()
            self.navigationController?.pushViewController(webViewController, animated: true)
        case "termsService":
            let webViewController = RdbViewUtils.shared.createTermService()
            self.navigationController?.pushViewController(webViewController, animated: true)
        default:
            break
        }
        
    }

    func getSettingsList() -> [[RdbSettingModel]]{
        return [
            [
                ["iconName": "setting_star", "title": "setting_star".localized, "identifier": "rateUs"],
                ["iconName": "setting_share", "title": "setting_share".localized, "identifier": "share"],
                ["iconName": "setting_global", "title": "setting_global".localized, "identifier": "language"],
                ["iconName": "setting_color", "title": "setting_color".localized, "identifier": "theme"]
            ].kj.modelArray(RdbSettingModel.self),
            [
                ["iconName": "setting_policy", "title": "setting_policy".localized, "identifier": "privacyPolicy"],
                ["iconName": "setting_terms", "title": "setting_terms".localized, "identifier": "termsService"]
            ].kj.modelArray(RdbSettingModel.self)
        ]
    }
    
    deinit{
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.isLayoutChanged {
            self.isLayoutChanged = false
            self.tableView.reloadData()
            guard let rootController = UIApplication.shared.fmKeyWindow?.rootViewController as? UITabBarController else {
                return
            }
            rootController.selectedIndex = 0
        }
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class RdbSettingTableViewCell: UITableViewCell{
    static let identified = "RdbSettingTableViewCell"
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = RdbColor.background.content.color
        
        self.contentView.addSubview(iconImageView)
        self.contentView.addSubview(titleTextLabel)
        self.contentView.addSubview(arrowImageView)
        
        let view = UIView()
        view.backgroundColor = UIColor.init(white: 0.4, alpha: 0.4)
        
        self.selectedBackgroundView = view
        
        self.iconImageView.snp.makeConstraints{
            $0.centerY.equalToSuperview()
            $0.leading.equalTo(16)
            $0.size.equalTo(CGSize(width: 18, height: 18))
        }
        self.titleTextLabel.snp.makeConstraints{
            $0.centerY.equalToSuperview()
            $0.leading.equalTo(42)
        }
        self.arrowImageView.snp.makeConstraints{
            $0.centerY.equalToSuperview()
            $0.trailing.equalTo(-16)
            $0.size.equalTo(CGSize(width: 16, height: 16))
        }
    }
    
    func configData(_ model: RdbSettingModel){
        self.iconImageView.image = UIImage(named: model.iconName)
        self.titleTextLabel.text = model.title
        self.arrowImageView.image = UIImage(named: "com_arrow_push")?.rtlImage()
    }
    lazy var iconImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    lazy var titleTextLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.white
        label.font = UIFont.regular(14)
        return label
    }()
    
    lazy var arrowImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
